package com.ui.zhong.webview

import android.app.Activity
import android.util.Log
import android.view.ViewGroup
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
import com.compose.ui.refresh.SwipeRefreshLayout
import com.ui.zhong.webview.webviewproc.ComposeWebView
import com.ui.zhong.webview.webviewproc.settings.WebViewDefaultSettings
import kotlinx.coroutines.delay

private const val TAG = "InternalComposeWebView"
@Composable
fun InternalComposeWebView(
    url: String,
    webViewTitle: MutableState<String>? = null,
    needRefresh: Boolean = true
) {
    val context = LocalContext.current
    val webViewComposeStatus = remember {
        mutableStateOf(ComposeWebViewStatus.LOADING)
    }

    val customWebView = remember {
        ComposeWebView(context).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )

            webViewClient = WebViewClient()

            WebViewDefaultSettings.getInstance().setSettings(this)

            registerWebViewCallBack(object : WebViewCallback {
                override fun pageStarted(url: String) {

                }

                override fun pageFinished(url: String) {
                    webViewComposeStatus.value = ComposeWebViewStatus.SHOW_CONTENT
                }

                override fun onError() {
                    Log.d(TAG,"")
                }

                override fun updateTitle(title: String) {
                    if (webViewTitle != null) {
                        webViewTitle.value = title
                    }
                }
            })

            loadUrl(url)
        }
    }

    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(13.dp, 0.dp)
                .requiredHeight(56.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Image(
                painter = painterResource(R.drawable.ic_back),
                contentDescription = null,
                modifier = Modifier.clickable {
                   // (context as Activity).finish()
                    Log.d(TAG,"customWebView: canGoBac: ${customWebView.canGoBack()}")
                    if(customWebView.canGoBack()){
                        customWebView.goBack()
                    }else{
                        (context as Activity).finish()
                    }
                }
            )

            Text(
                modifier = Modifier.fillMaxWidth(),
                text = webViewTitle?.value?:"",
                textAlign = TextAlign.Center,
                color = Color.White
            )
        }

        LoadingFeedbackComposable(webViewStatus = webViewComposeStatus) {
            var refreshing by remember { mutableStateOf(false) }
            LaunchedEffect(refreshing) {
                if (refreshing) {
                    delay(2000)
                    refreshing = false
                }
            }

            if (needRefresh) {
                SwipeRefreshLayout(
                    isRefreshing = refreshing,
                    onRefresh = { refreshing = true }
                ) {
                    LazyColumn {
                        item {
                            AndroidView(factory = {
                                customWebView
                            }, update = {

                            })
                        }
                    }
                }
            } else {
                AndroidView(factory = { customWebView })
            }
        }


    }



}

@Composable
fun LoadingFeedbackComposable(
    webViewStatus: MutableState<ComposeWebViewStatus>,
    content: @Composable () -> Unit
) {
    when (webViewStatus.value) {
        ComposeWebViewStatus.LOADING -> {
            val lottieComposition by rememberLottieComposition(
                spec = LottieCompositionSpec.RawRes(R.raw.walkthrough)
            )

            val lottieAnimationState by animateLottieCompositionAsState(
                composition = lottieComposition,
                iterations = Int.MAX_VALUE,
                isPlaying = true,
                restartOnPlay = true
            )

            LottieAnimation(
                modifier = Modifier.fillMaxSize(),
                composition = lottieComposition,
                progress = {
                    if (webViewStatus.value == ComposeWebViewStatus.LOADING) lottieAnimationState else 0f
                }
            )
        }
        ComposeWebViewStatus.EMPTY -> {
            val lottieComposition by rememberLottieComposition(
                spec = LottieCompositionSpec.RawRes(R.raw.walkthrough)
            )
            val lottieAnimationState by animateLottieCompositionAsState(
                composition = lottieComposition,
                iterations = 1,
                isPlaying = true,
                restartOnPlay = true
            )

            LottieAnimation(
                modifier = Modifier.fillMaxSize(),
                composition = lottieComposition,
                progress = {
                    lottieAnimationState
                }
            )
        }
        ComposeWebViewStatus.SHOW_CONTENT -> {
            content()
        }
        ComposeWebViewStatus.LOAD_MORE_FAILED -> {
            content()
            Toast.makeText(LocalContext.current, "加载更多失败，请重试....", Toast.LENGTH_SHORT).show()
        }
    }
}


enum class ComposeWebViewStatus {
    LOADING,
    SHOW_CONTENT,
    EMPTY,
    LOAD_MORE_FAILED
}
